package server

import (
	"context"
	"errors"
	"hotel-app/common/models/mysql"
	"hotel-app/common/proto/hotel"
	"hotel-app/cont"
	"math/rand"
	"time"
)

func SendSms(in *hotel.SendSmsReq) (*hotel.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000
	if len(in.Mobile) != 11 {
		return nil, errors.New("该手机号格式错误")
	}
	/*sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, errors.New("错误")
	}
	if *sms.Body.Code != "OK" {
		return nil, errors.New(*sms.Body.Message)
	}*/
	cont.Rdb.Set(context.Background(), "SendSms"+in.Source+in.Mobile, code, time.Minute*10)
	return &hotel.SendSmsResp{Greet: "发送成功"}, nil
}
func UserLogin(in *hotel.UserLoginReq) (*hotel.UserLoginResp, error) {
	get := cont.Rdb.Get(context.Background(), "SendSmsLogin"+in.Mobile)
	if get.Val() != in.Code {
		return nil, errors.New("验证码错误")
	}
	user := &mysql.User{}
	mobile, err := user.FindUserByMobile(in)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if mobile.ID == 0 {
		return nil, errors.New("没有该用户")
	}
	return &hotel.UserLoginResp{Greet: "登录成功"}, nil
}

func OrderList(in *hotel.OrderListReq) (*hotel.OrderListResp, error) {
	var Order []*mysql.Order
	cont.DB.Find(&Order)
	var list []*hotel.OrderList
	for _, o := range Order {
		list = append(list, &hotel.OrderList{
			OrderSn:    o.OrderSn,
			HotelName:  o.HotelName,
			HouseType:  o.HouseType,
			Name:       o.Name,
			StartTime:  o.StartTime,
			EndTime:    o.EndTime,
			Num:        int64(o.Num),
			CountPrice: float32(o.CountPrice),
			Person:     o.Person,
			Status:     int64(o.Status),
		})
	}
	return &hotel.OrderListResp{List: list}, nil
}
func OrderListByUser(in *hotel.OrderListByUserReq) (*hotel.OrderListByUserResp, error) {
	var Order []*mysql.Order
	err := cont.DB.Where("user_id=?", in.UserId).Find(&Order).Error
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var list []*hotel.OrderListByUser
	for _, o := range Order {
		list = append(list, &hotel.OrderListByUser{
			OrderSn:    o.OrderSn,
			HotelName:  o.HotelName,
			HouseType:  o.HouseType,
			Name:       o.Name,
			StartTime:  o.StartTime,
			EndTime:    o.EndTime,
			Num:        int64(o.Num),
			CountPrice: float32(o.CountPrice),
			Person:     o.Person,
			Status:     int64(o.Status),
		})
	}
	return &hotel.OrderListByUserResp{List: list}, nil
}
